package com.lv.dhart.manager;

import android.os.Environment;

import com.lv.dhart.api.Apiserivce;
import com.lv.dhart.constant.ApiPathConstant;
import com.lv.dhart.interceptor.TokenInterceptor;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {
    private static RetrofitManager retrofitManager;
    Retrofit retrofit;

    public RetrofitManager() {
        // 缓存目录
        File file = new File(Environment.getExternalStorageDirectory(), "/okhttp_cache/");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 缓存大小
        int cacheSize = 10 * 1024 * 1024;
        OkHttpClient client = new OkHttpClient.Builder()
                .cache(new Cache(file, cacheSize))
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .addInterceptor(new TokenInterceptor()) //添加判断token是否过期的拦截器
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .build();
        retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .baseUrl(ApiPathConstant.API_AS_BASE_URL)
                .build();

    }

    public static RetrofitManager getRetrofitManager() {
        if (retrofitManager == null) {
            synchronized (RetrofitManager.class) {
                retrofitManager = new RetrofitManager();
            }
        }
        return retrofitManager;
    }

    private Apiserivce apiService;

    public Apiserivce getApiService() {
        if (apiService == null) {
            apiService = retrofit.create(Apiserivce.class);
        }
        return apiService;
    }

}